package com.forum.module.system.service.auth;

import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.shaded.com.google.common.annotations.VisibleForTesting;
import com.forum.framework.common.constant.CacheConstants;
import com.forum.framework.common.enums.CommonStatusEnum;
import com.forum.framework.common.enums.UserTypeEnum;
import com.forum.framework.common.exception.util.ServiceExceptionUtils;
import com.forum.framework.common.util.object.BeanUtils;
import com.forum.framework.common.util.servlet.ServletUtils;
import com.forum.framework.redis.core.RedisCache;
import com.forum.module.system.controller.admin.auth.vo.AuthLoginReqVO;
import com.forum.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import com.forum.module.system.controller.admin.auth.vo.AuthRegisterReqVO;
import com.forum.module.system.controller.admin.auth.vo.AuthRegisterRespVO;
import com.forum.module.system.convert.auth.AuthConvert;
import com.forum.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.forum.module.system.dal.dataobject.role.RoleDO;
import com.forum.module.system.dal.dataobject.user.UserDO;
import com.forum.module.system.dal.dataobject.user_role.UserRoleDO;
import com.forum.module.system.enums.logger.LoginLogTypeEnum;
import com.forum.module.system.enums.logger.LoginResultEnum;
import com.forum.module.system.service.oauth2.OAuth2TokenService;
import com.forum.module.system.service.role.RoleService;
import com.forum.module.system.service.user.UserService;
import com.forum.module.system.service.user_role.UserRoleService;
import jakarta.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Objects;
import java.util.Optional;

import static com.forum.module.system.enums.ErrorCodeConstants.*;

/**
 * Auth Service 实现类
 *
 * @author zihan.ouyang
 */
@Service
public class AdminAuthServiceImpl implements AdminAuthService {
    private static final Logger logger = LoggerFactory.getLogger(AdminAuthServiceImpl.class);

    private final UserService userService;
    private final OAuth2TokenService oauth2TokenService;
    private final RedisCache redisConfig;
    private final RoleService roleService;

    private final UserRoleService userRoleService;

    public AdminAuthServiceImpl(UserService userService,
                                OAuth2TokenService oauth2TokenService,
                                Validator validator,
                                RedisCache redisCache,
                                RoleService roleService,
                                UserRoleService userRoleService) {
        this.userService = userService;
        this.oauth2TokenService = oauth2TokenService;
        this.redisConfig = redisCache;
        this.roleService = roleService;
        this.userRoleService = userRoleService;
    }

    @Override
    public UserDO authenticate(String username, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 校验账号是否存在
        UserDO user = userService.getUserByUsername(username);
        if (user == null) {
            createLogLogin(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw ServiceExceptionUtils.exception(USER_PASSWORD_ERROR);
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLogLogin(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw ServiceExceptionUtils.exception(USER_PASSWORD_ERROR);
        }
        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLogLogin(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw ServiceExceptionUtils.exception(USER_NOT_ENABLE);
        }
        return user;
    }

    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
        // 校验验证码
        validateCaptcha(reqVO);
        // 使用账号密码，进行登录
        UserDO user = authenticate(reqVO.getUsername(), reqVO.getPassword());

        UserRoleDO userRoleDO = userRoleService.selectByUserId(user.getId());

        RoleDO roleDO = roleService.selectById(userRoleDO.getRoleId());

        // 创建 Token 令牌
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, roleDO.getName());
    }

    @Override
    public AuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken);
        return null;
    }

    @Override
    public AuthRegisterRespVO register(AuthRegisterReqVO reqVO) {
        // 1. 校验验证码
        validateCaptcha(reqVO);

        // 2. 校验用户名是否已存在
        Long userId = userService.registerUser(reqVO);
        return BeanUtils.toBean(userId, AuthRegisterRespVO.class);
    }

    @Override
    public void logout(String token) {
        // 删除访问令牌
        OAuth2AccessTokenDO oAuth2AccessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (oAuth2AccessTokenDO == null) {
            return;
        }
        // 删除成功
    }

    private void createLogLogin(Long userId, String username, LoginLogTypeEnum logType, LoginResultEnum loginResultEnum) {
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResultEnum.getResult())) {
            userService.updateUserLogin(userId, ServletUtils.getClientIP());
        }
    }

    @VisibleForTesting
    void validateCaptcha(AuthLoginReqVO reqVO) {
        // todo 如果验证码关闭，则不进行校验
        // 校验验证码
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + reqVO.getUuid();
        String captcha = (String) redisConfig.get(verifyKey);
        if (captcha == null) {
            logger.info("验证码已失效, {}", reqVO.getUsername());
            throw ServiceExceptionUtils.exception(USER_LOGIN_CAPTCHA_EXPIRE);
        }
        redisConfig.delete(verifyKey);
        if (!reqVO.getCode().equalsIgnoreCase(captcha)) {
            logger.info("验证码不正确, {}", reqVO.getUsername());
            createLogLogin(null, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.CAPTCHA_CODE_ERROR);
            throw ServiceExceptionUtils.exception(USER_LOGIN_CAPTCHA_ERROR);
        }
    }

    @VisibleForTesting
    void validateCaptcha(AuthRegisterReqVO reqVO) {
        // todo 如果验证码关闭，则不进行校验
        // 校验验证码
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + reqVO.getUuid();
        String captcha = (String) redisConfig.get(verifyKey);
        if (captcha == null) {
            logger.info("验证码已失效, {}", reqVO.getUsername());
            throw ServiceExceptionUtils.exception(USER_LOGIN_CAPTCHA_EXPIRE);
        }
        redisConfig.delete(verifyKey);
        if (!reqVO.getCode().equalsIgnoreCase(captcha)) {
            logger.info("验证码不正确, {}", reqVO.getUsername());
            throw ServiceExceptionUtils.exception(USER_LOGIN_CAPTCHA_ERROR);
        }
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.ADMIN;
    }

    private AuthLoginRespVO createTokenAfterLoginSuccess(Long userId, String username, LoginLogTypeEnum logType,String roleName) {
        createLogLogin(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessToken = oauth2TokenService.createAccessToken(userId, getUserType().getValue(), Collections.singletonList(roleName));
        return AuthConvert.INSTANCE.convert(accessToken);
    }
}
